<?php

/**
 * tag标签管理model操作
 * @author  xiaobai
 * @date    2018-01-17
 */

namespace app\common\model;

use app\common\model\Common;

class Tag extends Common
{
    const TYPE_NEWS = 1;    // 文章
    const TYPE_ASK  = 2;    // 问答
    const TYPE_DIVE = 3;    // 约潜潜点

    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime'; // 自动写入时间，格式为Y-m-d H:i:s

    /**
     * 获取type类型内容
     * @return array
     */
    public function getType()
    {
        $data = array(
            self::TYPE_NEWS => '文章',
            self::TYPE_ASK  => '问答',
            self::TYPE_DIVE => '约潜',
        );
        return $data;
    }

    /**
     * 保存tag标签数据信息
     * @param  array $data  tag标签信息
     * @param  int $type    tag标签类型
     * @return array
     */
    public function saveData($data = array(), $type = self::TYPE_NEWS)
    {
        $data    = array_unique($data);     // 去重操作
        $tag_ids = array();
        foreach ($data as $key=>$val) {
            $where  = array('name'=>$val, 'type'=>$type);
            $tag_id = $this->where($where)->value('id');
            if (empty($tag_id)) {
                $tag_data = array(
                    'name'        => $val,
                    'type'        => $type,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                );
                $tag_id = $this->insertGetId($tag_data);
            }
            $tag_ids[$key] = $tag_id;
        }
        return $tag_ids;
    }

    /**
     * 获取热门问答标签
     * @param int $limit        获取数量
     * @param string $order     排序方式，默认数量倒序 id倒序
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getHotAskTag($limit = 20, $order = 'num desc, id desc')
    {
        $key  = 'getHotAskTag_'.md5($limit.$order);
        $list = cache($key);
        if (empty($list)) {
            $where = array('type'=>self::TYPE_ASK);
            $list  = $this->where($where)->order($order)->limit($limit)->select();
            if (!empty($list)) {
                cache($key, $list, 3600*24*7);
            } else {
                $list = array();
            }
        }

        return $list;
    }

    /**
     * 获取热门约潜标签
     * @param int $limit        获取数量
     * @param string $order     排序方式，默认数量倒序 id倒序
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getHotDiveTag($limit = 20, $order = 'num desc, id desc')
    {
        $key  = 'getHotDiveTagg_'.md5($limit.$order);
        $list = cache($key);
        if (empty($list)) {
            $where = array('type'=>self::TYPE_DIVE);
            $list  = $this->where($where)->order($order)->limit($limit)->select();
            if (!empty($list)) {
                cache($key, $list, 3600*24*7);
            } else {
                $list = array();
            }
        }

        return $list;
    }
}
